package com.lwm.transactional.annotation.config;


import com.lwm.transactional.annotation.utils.ConnectionUtils;
import com.lwm.transactional.annotation.utils.TransactionManager;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

/**
 * Spring 配置类 等同于bean.xml
 *
 * @date 2021/6/10 11:50
 * @since
 */
@EnableAspectJAutoProxy
@Configuration
@ComponentScan(basePackages = {"com.lwm"})
@PropertySource("classpath:jdbc.properties")
public class SpringConfiguration {

    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.name}")
    private String name;
    @Value("${jdbc.password}")
    private String password;

    @Bean(name = "queryRunner")
    @Scope("prototype")
    public QueryRunner getQueryRunner(DataSource dataSource) {
        return new QueryRunner(dataSource);
    }

    @Bean(name = "dataSource")
    public DataSource getDataSource() {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(name);
        dataSource.setPassword(password);
        dataSource.setJdbcUrl(url);
        try {
            dataSource.setDriverClass(driver);
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
        return dataSource;
    }

    @Bean(name = "connectionUtils")
    public ConnectionUtils getConnectionUtils(DataSource dataSource) {
        return new ConnectionUtils(dataSource);
    }

    @Bean(name = "transactionManager")
    public TransactionManager getTransactionManager(ConnectionUtils connectionUtils) {
        return new TransactionManager(connectionUtils);
    }
}
